from flask import Blueprint, request, jsonify, current_app, send_file,g
from .services import OperationService
import os
from app.config import Config
from app.database.connector import Database

operation_bp = Blueprint('operation', __name__)

@operation_bp.before_request
def init_services():
    """初始化服务，确保每个请求都有新的数据库连接"""
    g.db = Database()
    g.operation_service = OperationService(db=g.db)

@operation_bp.teardown_request
def close_db(exc):
    """请求结束时关闭数据库连接"""
    db = g.pop('db', None)
    if db is not None:
        db.close()

@operation_bp.route('/list', methods=['GET'])
def get_operation_list():
    """获取操作日志列表"""
    page = int(request.args.get('page', 1))
    page_size = int(request.args.get('pageSize', 10))
    filters = {
        'username': request.args.get('username'),
        'filename': request.args.get('filename'),
        'operation_type': request.args.get('operation_type[value]')
    }
    
    result, total = g.operation_service.get_operation_list(page, page_size, filters)

    # 为每条记录的 report_url 添加 API_URL 前缀
    for item in result:
        if item.get('report_url'):
            item['report_url'] = f"{Config.API_URL}{item['report_url']}"

    return jsonify({
        'items': result,
        'total': total,
        'page': page,
        'pageSize': page_size
    })

@operation_bp.route('/report/<path:filename>', methods=['GET'])
def download_report(filename):
    """下载操作报告"""
    try:
        report_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], 'reports')
        return send_file(
            os.path.join(report_dir, filename),
            as_attachment=True,
            download_name=filename
        )
    except Exception as e:
        current_app.logger.error(f"下载报告失败: {str(e)}")
        return jsonify({'error': '报告文件不存在'}), 404